const express = require("express");
const route = express.Router(); // 实例化一个路由对象
const sd = require("silly-datetime");
// 引入连接池
const pool = require("../../sql/index");
const path = require("path"); //系统路径模块
const fs = require("fs"); //文件模块
const superagent = require("../../reptile/index");

// 分页排序接口（带有模糊搜索查询）
route.get("/api/getStandardType", (req, res) => {
  let { current, pageSize, name, home, age, status } = req.query;
  if (!current || !pageSize) {
    res.send({ code: 500, msg: "参数错误!" });
    return;
  }
  //拼接sql
  let sql = `select id,name,age,home,remark,status,updateTime from people_table where  is_delete_status =1`;
  let sql2 = `select count(1) as total from people_table where  is_delete_status =1`;

  if (name) {
    sql += ` and name like "%${name}%"`;
    sql2 += ` and name like "%${name}%"`;
  }
  if (age) {
    sql += ` and age like "%${age}%"`;
    sql2 += ` and age like "%${age}%"`;
  }
  if (home) {
    sql += ` and home like "%${home}%"`;
    sql2 += ` and home like "%${home}%"`;
  }
  if (status) {
    sql += ` and status like "%${status}%"`;
    sql2 += ` and status like "%${status}%"`;
  }
  sql += ` order by updateTime desc`;
  let total = 0;
  pool.query(sql2, (err, data) => {
    if (err) throw err;
    total = data[0].total;
  });
  let n = (current - 1) * pageSize;
  sql += ` limit ${n}, ${pageSize}`;
  pool.query(sql, (err, data) => {
    if (err) throw err;
    //处理时间
    if (data && data.length > 0) {
      data.map((v) => {
        v.updateTime = sd.format(v.updateTime, "YYYY-MM-DD HH:mm");
      });
    }
    let apiRes = {
      code: 1,
      msg: "操作成功",
      data,
      total,
      current
    };
    res.send(apiRes);
  });
});

// 删除某一条数据的接口 常用做法，逻辑删除；
route.delete("/api/deleteStandardTypeById", (req, res) => {
  let { id } = req.query;
  if (!id) {
    res.send({ code: 500, msg: "参数错误!" });
    return;
  }
  const sql = `UPDATE people_table SET is_delete_status = 0 WHERE id = ${id}`;
  pool.query(sql, (err, data) => {
    if (err) throw err;
    if (data.affectedRows > 0) {
      res.send({ code: 1, msg: "删除成功!" });
    } else {
      res.send({ code: 0, msg: "删除失败！" });
    }
  });
});

// 批量删除接口
route.delete("/api/deleteStandardTypeByIds", (req, res) => {
  let { ids } = req.query;
  let sql = `UPDATE people_table SET is_delete_status = 0 WHERE id in (${ids})`;
  pool.query(sql, (err, data) => {
    if (err) throw err;
    if (data.affectedRows > 0) {
      res.send({ code: 1, msg: "批量操作成功!" });
    } else {
      res.send({ code: 0, msg: "批量操作失败！" });
    }
  });
});

// 新增数据接口
route.post("/api/addStandardType", (req, res) => {
  let { name, age, home, remark } = req.body;
  if (!name || !age || !home) {
    res.send({ code: 500, msg: "参数错误!" });
    return;
  }
  const time = sd.format(new Date(), "YYYY-MM-DD HH:mm");
  const sql = `insert into people_table(name, age, home, remark,updateTime, status, is_delete_status) values("${name}", "${age}", "${home}", "${remark}","${time}", 0 , 1 )`;
  pool.query(sql, (err, data) => {
    if (err) throw err;
    if (data.affectedRows > 0) {
      res.send({ code: 1, msg: "新增成功" });
    } else {
      res.send({ code: 0, msg: "新增失败" });
    }
  });
});

// 获取详情
route.get("/api/getStandardTypeById", (req, res) => {
  let { id } = req.query;
  if (!id) {
    res.send({ code: 500, msg: "参数错误!" });
    return;
  }
  const sql = `select * from people_table where id=${id}`;
  pool.query(sql, (err, data) => {
    if (err) throw err;
    res.send({
      code: 1,
      msg: "操作成功",
      data: {
        rows: data
      }
    });
  });
});

// 编辑
route.post("/api/updateStandardTypeById", (req, res) => {
  let { id, name, age, home, remark } = req.body;
  if (!id || !name || !age || !home || !remark) {
    res.send({ code: 500, msg: "参数错误!" });
    return;
  }
  const time = sd.format(new Date(), "YYYY-MM-DD HH:mm");
  const sql = `update people_table set name="${name}", age="${age}", home="${home}", remark="${remark}",updateTime="${time}" where id=${id}`;

  pool.query(sql, (err, data) => {
    if (err) throw err;
    if (data.affectedRows > 0) {
      res.send({
        code: 1,
        msg: "修改成功!"
      });
    } else {
      res.send({
        code: 0,
        msg: "修改失败!"
      });
    }
  });
});

// 启用停用
route.put("/api/updateStatusById", (req, res) => {
  let { id, targetStatus } = req.body;
  if (!id) {
    res.send({ code: 500, msg: "参数错误!" });
    return;
  }
  const time = sd.format(new Date(), "YYYY-MM-DD HH:mm");
  const sql = `update people_table set status=${targetStatus},updateTime="${time}" where id=${id}`;
  pool.query(sql, (err, data) => {
    if (err) throw err;
    if (data.affectedRows > 0) {
      res.send({
        code: 1,
        msg: "状态更新成功!"
      });
    } else {
      res.send({
        code: 0,
        msg: "状态更新失败!"
      });
    }
  });
});

// 批量启用停用
route.patch("/api/updateStatusByIds", (req, res) => {
  let { ids, targetStatus } = req.body;

  if (!ids) {
    res.send({ code: 500, msg: "参数错误!" });
    return;
  }
  const time = sd.format(new Date(), "YYYY-MM-DD HH:mm");
  const sql = `UPDATE people_table SET status=${targetStatus},updateTime="${time}" WHERE id in (${ids})`;

  console.log("sql", sql);

  pool.query(sql, (err, data) => {
    if (err) throw err;
    if (data.affectedRows > 0) {
      res.send({ code: 1, msg: "批量操作成功!" });
    } else {
      res.send({ code: 0, msg: "批量操作失败！" });
    }
  });
});

// 获取今日详情
route.get("/api/getTodayDetail", async (req, res) => {
  let one = await superagent.getOne(); //获取每日一句
  let two = await superagent.getSoup(); //获取鸡汤
  if (one) {
    res.send({
      code: 1,
      msg: "操作成功",
      data: {
        todaySay: one,
        Soup: two.content || ""
      }
    });
  }
});

// 获取今日微博top
route.get("/api/getTopByweibo", async (req, res) => {
  const content = await superagent.getHotSearchList();
  res.send({
    code: 1,
    msg: "操作成功",
    data: content
  });
});

module.exports = route; // 暴露出去方便管理
